const cloud = require('wx-server-sdk');
// 初始化 cloud
cloud.init({
    // API 调用都保持和云函数当前所在环境一致
    env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database();
const _ = db.command;


/**
 * 这个示例将经自动鉴权过的小程序用户 openid 返回给小程序端
 * 
 * event 参数包含小程序端调用传入的 data
 * 
 */
const get = (collectionName, list, needQuery) => {
    return async(event, context) => {
        const response = {};
        let query = {};
        if (needQuery) {
            query = event.query;
        }
        const { OPENID } = cloud.getWXContext();
        try {
            await db.collection(collectionName)
                .where({
                    owner: _.eq(OPENID),
                    ...query
                })
                .get()
                .then((res) => {
                    if (list) {
                        response.body = res;
                    } else {
                        response.body = res && res[0] || null;
                    }

                    response.code = 200;
                })
                .catch((err) => {
                    response.code = 500;
                    response.error = err;
                })
        } catch (err) {
            console.log(err);
        }

        return response;
    }
}

modules.export = get;